package com.samsung.common.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.samsung.common.annotation.LoginAjaxAuth;
import com.samsung.common.util.BaseUtil;
import com.samsung.common.util.Constant;

import net.sf.json.JSONObject;

/**
 * 
 *	@ClassName: AuthAjaxInterceptor
 *	@Description: ajax请求拦截器，适用于控制器方法，使用时在相应方法上添加@LoginAjaxAuth注解即可
 *	@author pu.huang
 *	@date 2015年4月26日 上午10:22:44
 *
 */
public class AuthAjaxInterceptor extends HandlerInterceptorAdapter {

	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		if (handler.getClass().isAssignableFrom(HandlerMethod.class)) {
			LoginAjaxAuth authPassport = ((HandlerMethod) handler).getMethodAnnotation(LoginAjaxAuth.class);

			// 没有声明需要权限,或者声明不验证权限
			if (authPassport == null || authPassport.validate() == false) {
				return true;
			} else {
				// 权限验证逻辑
				if (request.getSession().getAttribute(Constant.LOGIN_TOKEN) != null) {
					return true;
				} else {
					// 如果验证失败 返回到登录界面
					response.setDateHeader("expries", -1);
					response.setHeader("Cache-Control", "no-cache");
					response.setHeader("Pragma", "no-cache");
					response.setCharacterEncoding("UTF-8");  
				    response.setContentType("application/json; charset=utf-8");
					JSONObject obj = new JSONObject();
					obj.put("success", false);
					obj.put("msg", "请先登录后操作");
					obj.put("cmd", Constant.AjaxCommand.LOGIN);
					
					StringBuffer callback = request.getRequestURL();
					String parms = request.getQueryString();
					if(BaseUtil.isNotEmpty(parms)) {
						callback.append("?");
						callback.append(parms);
						callback.append("&r=");
						callback.append(Math.random());
					}
					
					obj.put("callback", callback);
					obj.write(response.getWriter());
					
					return false;
				}
			}
		} else {
			return true;
		}
	}
}